package com.banshuibao.bsb_android.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AuthorizedResultModel;
import com.banshuibao.bsb_android.model.ExpertAnswerDetailModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.RequestAuthorizedModel;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.PriceUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.cunoraz.gifview.library.GifView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangpan on 2017/12/18.
 */

public class ExpertAnswerAdapter extends BaseAdapter {
    private final Activity context;
    private List<ExpertResultModel.DataBean> list;
    private MediaPlayerUtil mediaPlayerUtil;
    private boolean isCheck;
    private Dialog buyDialog;
    private String isVip;

    public ExpertAnswerAdapter(Activity context, boolean isCheck) {
        this.context = context;
        this.isCheck = isCheck;
        list = new ArrayList<>();
        mediaPlayerUtil = new MediaPlayerUtil(context);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(mediaPlayerPlayingListener);
        isVip = GetLoginInfo.getLoginInfoInstance(context).readUser().getVip();
    }

    public void setUpData(List<ExpertResultModel.DataBean> data) {
        if (list != null) {
            list.addAll(data);
            notifyDataSetChanged();
        }
    }

    public void setDownDate(List<ExpertResultModel.DataBean> data) {
        if (list != null) {
            list.clear();
            list.addAll(data);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public ExpertResultModel.DataBean getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        //if (view == null) {
        view = View.inflate(context, R.layout.item_home_answer, null);
        viewHolder = new ViewHolder();
        viewHolder.question = view.findViewById(R.id.title);
        viewHolder.head = view.findViewById(R.id.header);
        viewHolder.name = view.findViewById(R.id.name);
        viewHolder.post = view.findViewById(R.id.skill);
        viewHolder.tag = view.findViewById(R.id.tag);
        viewHolder.date = view.findViewById(R.id.time);
        viewHolder.buy = view.findViewById(R.id.buy);
        viewHolder.buy_tag = view.findViewById(R.id.buy_tag);
        viewHolder.buy_price = view.findViewById(R.id.buy_price);
        viewHolder.more = view.findViewById(R.id.more);
        viewHolder.count = view.findViewById(R.id.count);
        viewHolder.tag.setVisibility(View.GONE);//始终隐藏
        view.setTag(viewHolder);
        /*} else {
            viewHolder = (ViewHolder) view.getTag();
        }*/
        final ExpertResultModel.DataBean dataBean = list.get(i);
        viewHolder.question.setText(dataBean.getQuestion());
        viewHolder.name.setText(dataBean.getName());
        if (!TextUtils.isEmpty(dataBean.getDuty())) {
            viewHolder.post.setText(dataBean.getDuty());
        } else {
            viewHolder.post.setText(dataBean.getPositiotn());
        }
        if (dataBean.getExpertVoices() != null && dataBean.getExpertVoices().size() > 0) {
            setMediaView(view, dataBean.getExpertVoices(), dataBean, i);
        }
        if (dataBean.getExpertVoices() != null && dataBean.getExpertVoices().size() > 2)
            viewHolder.more.setVisibility(View.VISIBLE);
        else
            viewHolder.more.setVisibility(View.GONE);
        ImageUtil.loadImageHead(context, dataBean.getHeadImg(), viewHolder.head);
        if (dataBean.getQuPrice() == 0) {
            viewHolder.buy_price.setVisibility(View.GONE);
            viewHolder.buy.setTextColor(context.getResources().getColor(R.color.free_price));
            viewHolder.buy.setText("限时免费听");
        } else {
            viewHolder.buy_price.setVisibility(View.VISIBLE);
            viewHolder.buy.setTextColor(context.getResources().getColor(R.color.charge_price));
            if (isVip.equals("0")) {
                viewHolder.buy_price.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                viewHolder.buy.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                viewHolder.buy.setText(PriceUtil.FormatDecimal(dataBean.getQuPrice()));
                viewHolder.buy_tag.setVisibility(View.VISIBLE);
            } else {
                viewHolder.buy_tag.setVisibility(View.GONE);
                viewHolder.buy_price.getPaint().setFlags(0);
                viewHolder.buy.getPaint().setFlags(0);
                viewHolder.buy_price.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
                viewHolder.buy.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
                viewHolder.buy.setText(PriceUtil.FormatDecimal(dataBean.getQuPrice()));
            }
        }
        viewHolder.date.setText(TimeUtil.format(dataBean.getCreateDate()));
        viewHolder.count.setText("听过:" + dataBean.getBuyNum() + "人");
        if (isCheck) {
            viewHolder.head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentManager.goPersonPageActivity(context, dataBean.getUserId());
                }
            });
        }
        return view;
    }

    private String voiceName, voiceContent;
    private MediaPlayer media;
    private String time;
    private String uuid = "";
    private int position = -1;

    private void setMediaView(View view, List<ExpertAnswerDetailModel.DataBean.VoicesBean> datas, ExpertResultModel.DataBean dataBean, int i) {
        final ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean = datas.get(0);
        VoiceViewHolder holder = new VoiceViewHolder();
        holder.text_tv = view.findViewById(R.id.text_tv);
        holder.show_tv = view.findViewById(R.id.show_tv);
        holder.voice_iv = view.findViewById(R.id.voice_iv);
        holder.voice_gif = view.findViewById(R.id.voice_gif);
        holder.mediaLayout1 = view.findViewById(R.id.media_layout1);
        holder.play = view.findViewById(R.id.play);
        if (position == i && TextUtils.equals(uuid, voicesBean.getUuid())) {
            voiceHolder = holder;
        }
        playAmi(position == i && TextUtils.equals(uuid, voicesBean.getUuid()), holder, TimeUtil.formatDuring(voicesBean.getVoiceTime()));
        setMediaData(holder, voicesBean, dataBean, i);

        VoiceViewHolder holder1 = new VoiceViewHolder();
        holder1.text_tv = view.findViewById(R.id.text_tv2);
        holder1.show_tv = view.findViewById(R.id.show_tv2);
        holder1.voice_iv = view.findViewById(R.id.voice_iv2);
        holder1.voice_gif = view.findViewById(R.id.voice_gif2);
        holder1.mediaLayout1 = view.findViewById(R.id.media_layout2);
        holder1.play = view.findViewById(R.id.play2);
        holder1.mediaLayout1.setVisibility(View.VISIBLE);
        holder.show_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        holder.show_tv.getPaint().setAntiAlias(true);//抗锯齿
        holder1.show_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        holder1.show_tv.getPaint().setAntiAlias(true);//抗锯齿
        ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean1 = null;
        if (datas.size() > 1) {
            voicesBean1 = datas.get(1);
            holder1.mediaLayout1.setVisibility(View.VISIBLE);
            if (position == i && TextUtils.equals(uuid, voicesBean1.getUuid())) {
                voiceHolder = holder1;
            }
            setMediaData(holder1, voicesBean1, dataBean, i);
        } else {
            holder1.mediaLayout1.setVisibility(View.GONE);
        }
        playAmi(position == i && TextUtils.equals(uuid, voicesBean1 != null ? voicesBean1.getUuid() : ""), holder1, voicesBean1 != null ? TimeUtil.formatDuring(voicesBean1.getVoiceTime()) : "");

    }

    private void playAmi(boolean b, VoiceViewHolder holder, String time) {
        if (b && media != null) {
            holder.text_tv.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
            holder.play.setEnabled(false);
            holder.voice_iv.setVisibility(View.GONE);
            holder.voice_gif.setVisibility(View.VISIBLE);
        } else {
            holder.voice_iv.setVisibility(View.VISIBLE);
            holder.voice_gif.setVisibility(View.GONE);
            holder.play.setEnabled(true);
            holder.play.setBackground(context.getResources().getDrawable(R.drawable.listenback));
            holder.text_tv.setText(time);
        }

    }

    private void setMediaData(final ExpertAnswerAdapter.VoiceViewHolder holder, final ExpertAnswerDetailModel.DataBean.VoicesBean voicesBean, final ExpertResultModel.DataBean dataBean, final int i) {
        holder.voice_gif.setGifResource(R.raw.play);
        if (position == i && TextUtils.equals(uuid, voicesBean.getUuid()) && media != null) {
            holder.text_tv.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
        } else
            holder.text_tv.setText(TimeUtil.formatDuring(voicesBean.getVoiceTime()));
        holder.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //审请权限
                getAuthorized(dataBean.getUuid(), voicesBean.getUuid(), TimeUtil.formatDuring(voicesBean.getVoiceTime()), holder, "voice", dataBean, i);
            }
        });
        holder.show_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //审请权限
                getAuthorized(dataBean.getUuid(), voicesBean.getUuid(), TimeUtil.formatDuring(voicesBean.getVoiceTime()), holder, "text", dataBean, i);
            }
        });
        if (TextUtils.equals(voicesBean.getUuid(), playUuid)) {
            holder.play.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
        } else {
            holder.play.setBackground(context.getResources().getDrawable(R.drawable.listenback));
        }
    }

    private ExpertAnswerAdapter.VoiceViewHolder voiceHolder;
    private boolean stop = false;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    if (!stop && voiceHolder != null && media != null) {
                        sendEmptyMessageDelayed(0, 1000);
                        voiceHolder.text_tv.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        voiceHolder.voice_iv.setVisibility(View.GONE);
                        voiceHolder.voice_gif.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    voiceHolder = (ExpertAnswerAdapter.VoiceViewHolder) msg.obj;
                    stop = false;
                    voiceHolder.play.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                    break;
                case 2:
                    if (voiceHolder == null || media == null)
                        return;
                    stop = true;
                    uuid = "";
                    position = -1;
                    voiceHolder.voice_iv.setVisibility(View.VISIBLE);
                    voiceHolder.voice_gif.setVisibility(View.GONE);
                    voiceHolder.play.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    voiceHolder.text_tv.setText(time);
                    playUuid = "";
                    media.seekTo(0);
                    media.pause();
                    media.stop();
                    media.reset();
                    media = null;
                    break;
                case 3:
                    if (media != null) {
                        if (media.isPlaying()) {
                            stop = true;
                            media.pause();
                            voiceHolder.voice_iv.setVisibility(View.VISIBLE);
                            voiceHolder.voice_gif.setVisibility(View.GONE);
                        } else {
                            stop = false;
                            sendEmptyMessageDelayed(0, 1000);
                            media.start();
                        }
                    }
                    break;
            }
        }
    };

    MediaPlayerUtil.MediaPlayerPlayingListener mediaPlayerPlayingListener = new MediaPlayerUtil.MediaPlayerPlayingListener() {
        @Override
        public void OnError(MediaPlayer mediaPlayer) {

        }

        @Override
        public void OnPrepared(MediaPlayer mediaPlayer) {
            //开始播放
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                handler.sendEmptyMessageDelayed(0, 1000);
            }
        }

        @Override
        public void OnCompletion(MediaPlayer mediaPlayer) {
            stopMedia();
        }
    };

    private String playUuid;

    /**
     * 调用援权接口是否可听可看
     */
    private void getAuthorized(String questionUuid, final String voiceUuid, final String during, final ExpertAnswerAdapter.VoiceViewHolder holder, final String tag, final ExpertResultModel.DataBean dataBean, final int i) {
        if (QuickDoubleClickable.isDoubleClick()) {
            return;
        }
        RequestAuthorizedModel requestAuthorizedModel = new RequestAuthorizedModel();
        requestAuthorizedModel.setUuid(questionUuid);
        requestAuthorizedModel.setVoiceId(voiceUuid);
        HttpUtil.doPost(Constants.Url.AUDIO_AUTHORIZED, requestAuthorizedModel, new HttpResponse(context, AuthorizedResultModel.class) {
            @Override
            public void onResult(Object obj) {
                AuthorizedResultModel resultModel = (AuthorizedResultModel) obj;
                AuthorizedResultModel.DataBean data = resultModel.getData();
                if (data != null) {
                    String type = data.getType();
                    if ("0".equals(type)) {
                        voiceName = data.getVoiceName();
                        voiceContent = data.getVoiceText();
                        if ("voice".equals(tag)) {
                            if (media != null) {
                                if (voiceUuid.equals(playUuid)) {
                                    handler.sendEmptyMessage(3);
                                } else {
                                    handler.sendEmptyMessage(2);
                                }
                            } else {
                                playUuid = voiceUuid;
                                time = String.valueOf(during);
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = holder;
                                handler.sendMessage(msg);
                                uuid = voiceUuid;
                                position = i;
                                playAudio(voiceName);
                            }
                        } else if ("text".equals(tag)) {
                            showText(voiceContent);
                        }

                    } else if ("1".equals(type)) {
                        voiceName = "";
                        voiceContent = "";
                        showBuy(dataBean);
                    }
                }
            }
        });
    }

    /**
     * 播放语音
     */
    private void playAudio(String name) {
        media = mediaPlayerUtil.getNetMedia(Constants.Url.AUDIO_PLAY + name);
    }

    public void showText(String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        builder.setMessage(content); //设置内容
        builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    /**
     * 是否购买
     */
    private void showBuy(final ExpertResultModel.DataBean dataBean) {
        buyDialog = DialogUtils.payDialog(context, "您可以支付" + dataBean.getQuPrice() + "元购买单次或支付365元购买会员卡收听所有语音!", dataBean.getUuid(), String.valueOf(dataBean.getQuPrice()), dataBean.getQuestion(), 5);
        if (!buyDialog.isShowing())
            buyDialog.show();
//        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
//        builder.setTitle("提示"); //设置标题
//        builder.setMessage("收听/查看此问题需要支付" + dataBean.getQuPrice() + "元"); //设置内容
//        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                IntentManager.goPayResultActivity(context, dataBean.getQuestion(), String.valueOf(dataBean.getQuPrice()), dataBean.getUuid(), 5);
//            }
//        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        //参数都设置完成了，创建并显示出来
//        builder.create().show();
    }


    public void stopMedia() {
        handler.sendEmptyMessage(2);
    }

    private class VoiceViewHolder {
        LinearLayout mediaLayout1, play;
        TextView text_tv, show_tv;
        ImageView voice_iv;
        GifView voice_gif;
    }

    private class AnswerViewHolder {
        TextView title, name, skill, time, buy, audio_icon, more;
        ImageView header;
    }

    class ViewHolder {
        ImageView head;
        TextView question;
        TextView name;
        TextView post;
        TextView date;
        ImageView tag;
        TextView buy;
        TextView buy_tag;
        TextView buy_price;
        ImageView more;
        TextView count;
    }

    public void clear() {
        stopMedia();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (media != null && media.isPlaying()) {
            media.pause();
            media.stop();
            media.release();
            media = null;
        }
        if (list != null) {
            list.clear();
        }

    }
}
